import app from './app';
import { logger } from './utils/logger';
import prisma from './lib/prisma';
import { redisClient } from './redis/client';

const port = process.env.PORT || 3000;

async function checkConnections() {
  try {
    // 测试数据库连接
    await prisma.$connect();
    logger.info('Database connection established');

    // 测试Redis连接
    await redisClient.get('test-connection');
    logger.info('Redis connection established');

    return true;
  } catch (error) {
    if (error instanceof Error) {
      logger.error('Connection check failed:', error.message);
    } else {
      logger.error('Unknown connection error occurred');
    }
    return false;
  }
}

async function startServer() {
  try {
    // 检查连接
    const isConnected = await checkConnections();
    if (!isConnected) {
      throw new Error('Failed to establish required connections');
    }

    // 启动服务器
    app.listen(port, () => {
      logger.info(`Server is running on port ${port}`);
      logger.info(`Environment: ${process.env.NODE_ENV}`);
    });

    // 优雅关闭
    const signals = ['SIGTERM', 'SIGINT'];
    signals.forEach(signal => {
      process.on(signal, async () => {
        logger.info(`${signal} received. Starting graceful shutdown...`);
        
        try {
          // 断开数据库连接
          await prisma.$disconnect();
          logger.info('Database connection closed');

          // 断开Redis连接
          await redisClient.quit();
          logger.info('Redis connection closed');

          // 退出进程
          process.exit(0);
        } catch (error) {
          logger.error('Error during graceful shutdown:', error);
          process.exit(1);
        }
      });
    });

  } catch (error) {
    logger.error('Failed to start server:', error);
    process.exit(1);
  }
}

startServer();
